<script lang="ts" setup>
import { reactive, ref, shallowRef, onMounted, onActivated } from 'vue'
import { useMap } from '@/hooks/useMap'
import { useActivated } from '@/hooks/useActivated'
import { useRoute } from 'vue-router'
import SearchPlace from '@/components/map/SearchPlace.vue'
import storeImg from '@/assets/map/operatorsInfo/store.png'
import redStoreImg from '@/assets/map/operatorsInfo/redstore.png'
import { queryStore } from '@/api/store'
import { StoreTableCol } from '@/api/store/types/store'
import { getToken } from '@/utils/cache/cookies'
import { ElMessage } from 'element-plus'
import { StoreStatus } from '@/types/enum'
defineOptions({
  name: 'StoreAMap'
})
const route = useRoute()
const params = reactive({
  storeName: route.query.storeName as string,
  phone: route.query.phone as string,
  name: route.query.name as string,
  status: route.query.status as StoreStatus,
  pageSize: route.query.pageSize as string,
  pageNum: route.query.pageNum as string
})
const center = reactive({
  longtitude: 0,
  latitude: 0
})

const loading = ref<boolean>(false)
const isInit = ref<boolean>(false)
const mapContainer = ref<HTMLDivElement>()
const markers = shallowRef<AMap.LabelMarker[]>([])
const data = ref<StoreTableCol[]>()
const labelsLayer = shallowRef<AMap.LabelsLayer>()
const { map, auto, initAmap, getAddress, placeSearch } = useMap(mapContainer, [
  Number(center.longtitude),
  Number(center.latitude)
])
/** 地图初始化 */
const getIcon: () => AMap.LabelMarkerIconOptions = () => {
  return {
    type: 'image', //图标类型，现阶段只支持 image 类型
    image: storeImg, //可访问的图片 URL
    size: [30, 30], //图片尺寸
    clipOrigin: [0, 0],
    clipSize: [59, 63]
  }
}
const getData = async () => {
  try {
    loading.value = true
    const res = await queryStore({
      ...params,
      token: getToken() ?? ''
    })
    if (res.statusCode === '0') {
      data.value = res.data.list
      handleCoverInit()
    } else {
      ElMessage.error('暂无数据')
    }
    loading.value = false
  } catch (error) {
    console.error(error)
  }
}
const handleCoverInit = () => {
  if (data.value!.length > 0) {
    const firstBike = data.value![0]
    center.longtitude = Number(firstBike.longtitude ?? 0)
    center.latitude = Number(firstBike.latitude ?? 0)
  }
  if (isInit.value && map.value) {
    if (labelsLayer.value) {
      labelsLayer.value.clear()
      map.value.removeLayer(labelsLayer.value)
      map.value.clearMap()
    }
    map.value?.setCenter([center.longtitude, center.latitude])
    labelsLayer.value = new AMap.LabelsLayer({
      zooms: [3, 20],
      zIndex: 1000,
      collision: false, //该层内标注是否避让
      allowCollision: true //不同标注层之间是否避让
    })

    map.value.add(labelsLayer.value)
    const normalMarker = new AMap.Marker({
      anchor: 'bottom-center',
      offset: [0, -63]
    })
    map.value?.add(normalMarker)
    data.value?.forEach((point: any) => {
      /** extData 用于确实点标记是否已被点击 */
      const curData = {
        position: new AMap.LngLat(Number(point.longtitude) ?? 0, Number(point.latitude) ?? 0),
        icon: getIcon(),
        rank: 1,
        zIndex: 16,
        extData: false
      }
      const labelMarker = new AMap.LabelMarker(curData)
      markers.value?.push(labelMarker)
      labelMarker.on('click', async (e: any) => {
        labelsLayer.value?.getAllOverlays()?.forEach((marker: any) => {
          marker.setExtData(false)
          marker.setTop(false)
          marker.setIcon({
            type: 'image', //图标类型，现阶段只支持 image 类型
            image: storeImg, //可访问的图片 URL
            size: [30, 30], //图片尺寸
            clipOrigin: [0, 0],
            clipSize: [59, 63]
          })
        })
        const position = e.data.data && e.data.data.position
        if (position) {
          /** 点标记是否置顶 */
          e.target.setTop(!e.target.getExtData())
          e.target.setIcon({
            type: 'image', //图标类型，现阶段只支持 image 类型
            image: e.target.getExtData() ? storeImg : redStoreImg, //可访问的图片 URL
            size: [30, 30], //图片尺寸
            clipOrigin: [0, 0],
            clipSize: [59, 63]
          })

          if (e.target.getExtData()) {
            normalMarker.hide()
          } else {
            const address: any = await getAddress(position[0], position[1])
            normalMarker.setContent(createContent(address))
            normalMarker.setPosition(position)
            normalMarker.show()
          }
          e.target.setExtData(!e.target.getExtData())
        }
      })
    })
    labelsLayer.value.add(markers.value)
  }
}
const createContent = (address: string) => {
  return `<div class="map-infowindow_location">
                  <span>门店位置:${address}</span>
              </div>
              `
}
onMounted(async () => {
  isInit.value = await initAmap()
  await getData()
})
/** 处理是否缓存 */
onActivated(() => {
  params.storeName = route.query.storeName as string
  params.phone = route.query.phone as string
  params.name = route.query.name as string
  params.status = route.query.status as StoreStatus
  params.pageSize = route.query.pageSize as string
  params.pageNum = route.query.pageNum as string
})
useActivated(
  params,
  { params },
  [
    { key: 'pageSize', path: 'params.pageSize' },
    { key: 'bikeCode', path: 'params.bikeCode' },
    { key: 'type', path: 'params.type' },
    { key: 'storeId', path: 'params.storeId' }
  ],
  getData,
  []
)
</script>

<template>
  <div class="xy-map-container">
    <div ref="mapContainer" id="map-container" v-loading="loading">
      <search-place :auto="auto" :map="map!" :place-search="placeSearch" />
    </div>
  </div>
</template>

<style scoped></style>
